package com.loyal.camerax.utils

import android.util.Log
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.view.CameraController
import com.loyal.camerax.config.PhotoConfig
import java.util.concurrent.Executor

object ControllerHelper {
    private const val TAG = "ControllerHelper.kt"

    /**拍照*/
    fun CameraController?.takePhotoByByteArray(
        config: PhotoConfig, cameraExecutor: Executor,
        savedCallback: ((success: Boolean) -> Unit)?
    ) {
        this?.takePicture(cameraExecutor, object : ImageCapture.OnImageCapturedCallback() {
            override fun onCaptureSuccess(image: ImageProxy) {
                super.onCaptureSuccess(image)
                savePicture(image, config, savedCallback)
            }

            override fun onError(e: ImageCaptureException) {
                Log.e(TAG, "Photo capture failed: ${e.message}", e)
            }
        })
    }

    /**切换前后相机*/
    fun CameraController?.switchCameraSelector() {
        val currentSelector = this?.cameraSelector
        val newSelector = if (CameraSelector.DEFAULT_FRONT_CAMERA == currentSelector) {
            CameraSelector.DEFAULT_BACK_CAMERA
        } else {
            CameraSelector.DEFAULT_FRONT_CAMERA
        }
        this?.cameraSelector = newSelector
    }

    fun CameraController?.hasBackCamera(): Boolean {
        return this?.hasCamera(CameraSelector.DEFAULT_BACK_CAMERA) ?: false
    }

    fun CameraController?.hasFrontCamera(): Boolean {
        return this?.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA) ?: false
    }

    fun CameraController?.canSwitchCamera(): Boolean {
        return hasBackCamera() && hasFrontCamera()
    }
}